<template>
  <div ref="liquidFillContainer" style="width: 100%; height: 100%"></div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from 'vue';
import * as echarts from 'echarts';
import 'echarts-liquidfill';

const liquidFillContainer = ref(null);
let chartInstance: any = null;

const props = defineProps({
  // 值
  value: {
    type: Number,
    default: 0.3 //0-1 数字  
  },
  // 标题
  title: {
    type: String,
    default: ''
  },
  // 水球大小
  radius: {
    type: String,
    default: '66%'
  },
  // 显示格式
  viewFormat: {
    type: String,
    default: 'ratio',  // ratio 比率 num 数字 other其他
  }
})

onMounted(() => {
  chartInstance = echarts.init(liquidFillContainer.value);

  const option = {
    title: {
      // 标题
      text: props.title,
      textStyle: {
        // 标题的样式
        color: '#fff', // 字体颜色
        fontFamily: 'Microsoft YaHei', // 字体
        fontSize: 16,
        fontWeight: '400',
        align: 'center', // 文字的水平方式
        baseline: 'middle',
        position: 'inside',
        verticalAlign: 'middle', // 文字的垂直方式
      },
      left: 'center', // 定位
      bottom: '0px',
    },
    grid: {
      top: '0px',
      containLabel: true,
    },
    series: [
      {
        type: 'liquidFill',
        radius: props.radius, //水球大小
        center: ['50%', '40%'],
        waveAnimation: true,
        color: [
          {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: '#138FE2',
              },
              {
                offset: 1,
                color: '#126ABC',
              },
            ],
            globalCoord: false,
          },
        ],
        data: [0.3, 0.3], // data个数代表波浪数
        amplitude: 10, //振幅
        backgroundStyle: {
          borderWidth: 2, //边框大小
          borderColor: 'rgba(17, 94, 176, 0.8)', //边框颜色
          color: 'rgba(17, 94, 176, 0.4)',
        },
        label: {
          normal: {
            textStyle: {
              fontSize: String(props.value).length > 7 ? 12 : 16,
              fontWeight: 'bold',
              color: '#fff',
            },
            formatter: () => {
              return  props.viewFormat == 'ratio'  ?   `${(props.value * 100)}%` : props.value // 文字显示
            },
          },
          
        },
        outline: {
          borderDistance: 0,
          itemStyle: {
            borderWidth: 4,
            borderColor: 'transparent',
          },
        },
      },
    ],
  };
  chartInstance.setOption(option);

  // 监听窗口大小变化，重新resize图表
  window.addEventListener('resize', () => {
    chartInstance.resize();
  });
});

onUnmounted(() => {
  chartInstance && chartInstance.dispose();
});
</script>
